package com.lagou.handler;

import com.lagou.request.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Method;

/**
 * @author xsl
 * @date 2021/3/13 15:00
 * @Description: UserServiceHandler
 */
@Configuration
public class UserServiceHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof RpcRequest) {
            RpcRequest request = (RpcRequest) msg;
            Class<?> clz = Class.forName(request.getClassName());
            Object bean = applicationContext.getBean(clz);
            Method method = clz.getMethod(request.getMethodName(), request.getParameterTypes());
            Object result = method.invoke(bean, request.getParameters());
            System.out.println("执行方法返回：" + result);
            //返回执行目标方法成功
            ctx.writeAndFlush(request);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        ctx.close();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
